/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package models;

import entidades.Usuario;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

/**
 *
 * @author Ruben
 */
public class UsuarioBean extends org.apache.struts.action.ActionForm {

    private Usuario usuario;
    private Conectar c;

    public Usuario getUsuario() {
        return usuario;
    }

    public void setUsuario(Usuario usuario) {
        this.usuario = usuario;
    }

    /**
     *
     */
    public UsuarioBean() {
        super();
        usuario=new Usuario();
        c= new Conectar();
        // TODO Auto-generated constructor stub
    }

     public boolean login() {
        boolean exito=false;
        try {

            
            PreparedStatement ps = c.crearQuery("select * "
                    + "from usuario "
                    + "where nom=? && pass=? LIMIT 1    ");
            ps.setString(1, usuario.getNom());
            ps.setString(2, usuario.getPass());
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                usuario.setIdUsuario(rs.getInt("idUsuario"));
                usuario.setNom(rs.getString("nom"));
                usuario.setPass(rs.getString("pass"));
                usuario.setAcc(rs.getInt("acc"));
                exito=true;
                
            }else{
                usuario=null;
            }
            return exito;
        } catch (SQLException ex) {
            usuario = null;
            return exito;
        }
    }
     
    public int registro(){
        
        try {
            
            PreparedStatement ps = c.crearQuery("insert into usuario (nom,pass) "
                    + "values(?,?)");
            ps.setString(1, usuario.getNom());
            ps.setString(2, usuario.getPass());
            return ps.executeUpdate();
        } catch (SQLException ex) {
            return -1;
        }
    }
    /**
     * This is the action called from the Struts framework.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param request The HTTP Request we are processing.
     * @return
     */
    public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
        ActionErrors errors = new ActionErrors();
        if (usuario.getNom() == null || usuario.getNom().length()< 1) {
            errors.add("nombre", new ActionMessage("error.nombre.required"));
            // TODO: add 'error.name.required' key to your resources
        }
        return errors;
    }
}
